class LoginTagLib {

	def loginControl = {
		if(session.user){
			out << "Hello ${session.user.name} "
			out << """ [${link(action:"logout", controller:"user"){"Logout"}}]"""
		} else {
			out << """[${link(action:"login", controller:"user"){"Login"}}]"""
		}
	}
	
	// Execute main body only if the user is logged in
	def ifLoggedIn = {attrs, body ->
		if (getUserName()) {
			out << body{}
		}
	}

	// Execute main body only if the user is NOT logged in
	def ifNotLoggedIn = {attrs, body ->
		if (!getUserName()) {
			out << body{}
		}
	}

	// Execute main body only if the user is logged in and has one of the roles requested
	def ifUserHasRole = {attrs, body ->
		if (userHasOneOfRequiredRoles(attrs.roles.split(/,/))) {
			out << body{}
		}
	}

	// Execute main body only if the user is logged in and has none of the roles requested
	def ifUserHasNoRole = {attrs, body ->
		if (!userHasOneOfRequiredRoles(attrs.roles.split(/,/))) {
			out << body{}
		}
	}

	// Output the signed on user name (if they are logged in)
	def loggedInUser = { attrs, body ->
		out << session.user.name
//		def username = getUserName()
//	    if (username) {
//			out << username
//		} else {
//			out << "chupamos"
//		}
	}

	/*
	 * Execute main body only if the user is logged in and is either an admin user (based on supplied roles) or
	 * if they were the creator of the bean (based on the supplied userName)
	 */
	def ifUserCanEdit = {attrs, body ->
		def userIsGood = false
		def adminRoles = attrs["adminRoles"]
		if (adminRoles) {
			userIsGood = userHasOneOfRequiredRoles(adminRoles.split(/,/))
		}
		if (!userIsGood) {

		 	def login = attrs["username"]
			def signedOnLogin = session?.user?.login;
		 	if (signedOnLogin && login == signedOnLogin) {
		 		userIsGood = true
		 	}

//		 	def userName = attrs["userName"]
//			def signedOnUserName = getUserName();
//		 	if (signedOnUserName && userName == signedOnUserName) {
//		 		userIsGood = true
//		 	}
		}
		if (userIsGood) {
			out << body{}
		}
	}


//	// Helper method to get the user name
//	def getUserName =  {sdf ->
//		//return request.remoteUser
//		return session.user.name
//	}


	protected getUserName() {
		return session?.user?.name
	}

	// Helper method to indicate if a user has at least one of the requested roles
	protected userHasOneOfRequiredRoles(def requiredRoles) {
		def userHasOneRole = false
		if (getUserName()) {
			requiredRoles.each {roleRequired ->
//				if (request.isUserInRole(roleRequired)) {
				if (session.user.role.equals(roleRequired)) {
					userHasOneRole = true
				}
			}
		}
		return userHasOneRole
//		return true
	}


//	// Helper method to indicate if a user has at least one of the requested roles
//	def userHasOneOfRequiredRoles = {requiredRoles ->
//		def userHasOneRole = false
//		if (getUserName()) {
//			requiredRoles.each {roleRequired ->
//				if (request.isUserInRole(roleRequired)) {
//					userHasOneRole = true
//				}
//			}
//		}
//		return userHasOneRole
//	}

//ifLoggedIn : Only execute the tag body if the user is logged in
//				<g:ifLoggedIn><g:link controller="logout"><g:message code="common.logout"/></g:link></g:ifLoggedIn>
//ifNotLoggedIn : Only execute the tag body if the user is not logged in
//				<g:ifNotLoggedIn><g:link controller="login"><g:message code="common.login"/></g:link></g:ifNotLoggedIn>
//loggedInUser : Output the user's username (if they are logged in!)
//				Welcome <g:loggedInUser/>
//ifUserHasRole : Only execute the tag body if the user is logged in and has at least one of the roles specified
//				<g:ifUserHasRole roles="ROLE_ADMIN,ROLE_EDITOR">
//					<g:link controller="article" action="create">Create a new article</g:link>
//				</g:ifUserHasRole>
//ifUserHasNoRole : Only execute the tag body if the user has none of the roles specified (or is not logged in)
//				<g:ifUserHasNoRole roles="ROLE_ADMIN,ROLE_EDITOR">
//					<p>To request that this article is deleted contact the editor!</p>
//				</g:ifUserHasNoRole>
//ifUserCanEdit : Only execute the tag body if the user is logged in and has either at least one of the roles specified or the same username as the supplied value
//				<g:ifUserCanEdit roles="ROLE_ADMIN" userName="${registeredUser?.createdBy}>
//					<g:link action="edit" id="${registeredUser.id}"><g:message code="common.edit.title"/></g:link>
//				</g:ifUserCanEdit>

//
//	def loginControl = {
//		attrs ->
//	  """ [${link(action:"logout", controller:"user"){"Logout"}}]"""
//		//    if(session.user){
//		//
//		////	      out << "Hello ${session.user}";
//		////      out << "Hello ${session.user.name} "
//		////      out << "Hello ${session?.user?.name}"
//		////      out << """ Hello ${session.user.name}  """
//		////	 [${link(action:"logout", controller:"user"){"Logout"}}]"""
//		//    } else {
//		//      out << """[${link(action:"login", controller:"user"){"Login"}}]"""
//		//    }
//	}

	// <g:loginControl />

	def eachInCollection = {
		//		attrs ->
		//		attrs['collection'].each{
		//			out << "<li>${it}</li>"
		//		}
		attrs ->
		out << "<li>UAU Funciona!!!</li>"
	}

	def isAdmin = { attrs, body ->
		def user = attrs['user']
		if(user != null && checkUserPrivs(user)) {
			out << body()
		}
	}


	def repeat = { attrs, body ->
		def i = Integer.valueOf( attrs["times"] )
		def current = 0
		i.times {
			// pass the current iteration as the groovy default arg "it"
			// then pass the result to "out" to send it to the view
			out << body( ++current )
		}
	}

	//<g:repeat times="3">
	//<p>Repeat this 3 times! Current repeat = ${it}</p>
	//</g:repeat>
	


	//  def isSupplier = {
	//	  if ((session?.user) && (session?.user.role == 'Supplier')) {
	//      out << "Hello ${session.user.name} "
	//      out << """[${link(action:"logout", controller:"user"){"Logout"}}]"""
	//	  out << "Bem vindo caraças!!!"
	//    } else {
	//      out << """[${link(action:"login", controller:"user"){"Login"}}]"""
	//    }
	//  }


}
